package com.wanglei.wc

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Spark02_wordcount {

  def main(args: Array[String]): Unit = {
    //
    val sparkConf = new SparkConf().setMaster("local[2]").setAppName("wc")
    val sc = new SparkContext(sparkConf)

    //
    val lines: RDD[String] = sc.textFile("datas")
    val words: RDD[String] = lines.flatMap(_.split(" "))
    val wordToOne: RDD[(String, Int)] = words.map(word => (word, 1))
    val wordGroup: RDD[(String, Iterable[(String, Int)])] = wordToOne.groupBy(t => t._1)
    val wordCount = wordGroup.map {
      case (_, list) => {
        list.reduce((t1, t2) => {
          (t1._1, t1._2 + t2._2)
        })
      }
    }

    val res: Array[(String, Int)] = wordCount.collect()
    res.foreach(println(_))

    //
    sc.stop()
  }

}
